<template>
    <el-submenu :index="idx" v-if="urlAvailible(routes)">
        <template slot="title">
            <i :class="icon"/>
            <span slot="title">{{title}}</span>
        </template>
        <el-menu-item v-for="item in routes" :key="item.url" :index="item.url" v-show="urlAvailible(item.url)">{{item.name}}</el-menu-item>
        <slot/>
    </el-submenu>
</template>

<script>
    import {mapGetters} from 'vuex'
    export default {
        name: "private-route",
        props:['routes','idx','title','icon'],
        data(){
            let auth = localStorage.getItem('auth') !== 'undefined' ? localStorage.getItem('auth') : '[]';
            let userInfo = localStorage.getItem('userInfo') !== 'undefined' ? localStorage.getItem('userInfo') : '{}';
            return {
                localAuth: JSON.parse(auth) || [],
                localUser: JSON.parse(userInfo) || {}
            }
        },
        computed: {
            ...mapGetters(['auth','user'])
        },
        mounted(){
            if(!this.user && this.localUser) {
                this.$router.replace('/');
            }
        },
        methods:{
            urlAvailible(url) {
                const auth =  this.auth && this.auth.menu ? this.auth : this.localAuth;  // 先从store中获取权限信息保证是实时的，如果页面刷新则采用localstorage中的数据
                if(auth && auth.menu){
                    return auth.menu.some(menu=>{
                        if (Array.isArray(url)) {
                            // return  url.indexOf(menu.url) > -1
                            return (
                                url.some(item => {
                                    return item.url === menu.url
                                })
                            )
                        } else {
                            return url === menu.url
                        }
                    })
                } else {
                    return false
                }
            }
        },
    }
</script>

<style scoped>

</style>